package com.lb.shopguide.ui.fragment.boss;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.ImCache;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.ImBean;
import com.lb.shopguide.entity.UpdateInfoBean;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.im.Preference.Preferences;
import com.lb.shopguide.im.Preference.UserPreferences;
import com.lb.shopguide.ui.activity.GuideActivity;
import com.lb.shopguide.ui.view.ClearTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.lb.shopguide.util.lb.ClickUtil;
import com.lb.shopguide.util.lb.LogoutHelper;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nimlib.sdk.AbortableFuture;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * Created by kang on 2018/1/4.
 */

public class FragmentBossLogin extends BaseCommonFragment {
    @BindView(R.id.ctb)
    ClearTitleBar ctb;
    @BindView(R.id.et_boss_name)
    EditText etBossName;
    @BindView(R.id.et_boss_pwd)
    EditText etBossPwd;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.chk_pwd)
    CheckBox chkPwd;

    private UpdateInfoBean updateInfoBean;
    private ImBean imBean;



    public static FragmentBossLogin newInstance(UpdateInfoBean updateInfoBean) {
        FragmentBossLogin fragment = new FragmentBossLogin();
        Bundle bundle = new Bundle();
        if (updateInfoBean != null) {
            bundle.putSerializable(AppConstant.UPDATE_BEAN, updateInfoBean);
        }
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_boss_login;
    }

    @Override
    public void initData() {
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.UPDATE_BEAN)) {
            updateInfoBean = (UpdateInfoBean) bundle.getSerializable(AppConstant.UPDATE_BEAN);
        }
    }

    @Override
    public void initView() {
        ctb.setLeftImageSrc(R.drawable.iv_boss_back);
        ctb.setLeftText("重新选择身份");
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ToastUtils.showShort("token过期");
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentBossLogin.class.getName();
    }

    private void savePreference(ImBean imBean, String token) {
        mUserConfigManager.setTerminalType(AppConstant.TERMINAL_TYPE_BOSS);
        mUserConfigManager.setUserId(imBean.getAccid());
        mUserConfigManager.setUserToken(token);
        mUserConfigManager.setAccId(imBean.getAccid());
        mUserConfigManager.setImToken(imBean.getToken());
        mUserConfigManager.save2Sp(true);
    }

    @OnClick(R.id.btn_login)
    void login() {
        if (!ClickUtil.isFastDoubleClick()) {
            sendRequestLogin();
        } else {
            ToastUtils.showShort("正在登录，请勿重复点击");
        }
    }

    @OnClick({R.id.image_left, R.id.tv_left})
    void leftClick() {
        pop();
    }

    @OnClick(R.id.chk_pwd)
    void checkPwd() {
        if (chkPwd.isChecked()) {
            etBossPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            etBossPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        etBossPwd.setSelection(etBossPwd.getText().length());
    }

    private void sendRequestLogin() {
        RequestBody body = getRequestBody();
        if (body == null) {
            return;
        }
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {
            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(response.getReturnContent().toString());
                        imBean = JsonUtil.getGson().fromJson(jsonObject.getString("imInfo"), ImBean.class);
                        String token = jsonObject.getString("token");
                        savePreference(imBean, token);
//                            loginPush(userBean);
                        loginIm();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        };
        ApiMethodBoss.bossLogin(new SimpleLbObserver<BaseResponse>(listener, otherListener), body,this, FragmentEvent.DESTROY_VIEW);
    }

    private void loginIm() {
        if (TextUtils.isEmpty(ImCache.getAccount())) {
            final String account = imBean.getAccid();
            final String token = imBean.getToken();
            // 登录
            AbortableFuture<LoginInfo> loginRequest = NimUIKit.login(new LoginInfo(account, token, AppConstant.YUNXIN_APPKEY), new RequestCallback<LoginInfo>() {
                @Override
                public void onSuccess(LoginInfo param) {
//                        onLoginDone();
                    ImCache.setAccount(account);
                    saveLoginInfo(account, token);
                    // 初始化消息提醒配置`
                    initNotificationConfig();
                    Intent intent = ((GuideActivity) _mActivity).getBossMainActivityIntent();
                    intent.putExtra(AppConstant.UPDATE_BEAN, updateInfoBean);
                    _mActivity.startActivity(intent);//顺序修改，修改问题，看看会不会有其他问题
                    _mActivity.finish();
                }

                @Override
                public void onFailed(int code) {
                    if (code == 302 || code == 404) {
//                        Toast.makeText(mContext, R.string.login_failed, Toast.LENGTH_SHORT).show();
                        sendRequestRefreshYXToken();
                    } else {
                        Toast.makeText(mContext, "im登录失败: " + code, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onException(Throwable exception) {
                    Toast.makeText(mContext, R.string.login_exception, Toast.LENGTH_LONG).show();
                }
            });
        } else {
            LogoutHelper.logout();
            loginIm();
        }
    }

    private RequestBody getRequestBody() {
        String name = etBossName.getText().toString();
        String pwd = etBossPwd.getText().toString();
        if (TextUtils.isEmpty(name)) {
            ToastUtils.showShort("请输入用户名");
            return null;
        }
        if (TextUtils.isEmpty(pwd)) {
            ToastUtils.showShort("请输入密码");
            return null;
        }
        HashMap hashMap = new HashMap();
        hashMap.put("userName", name);
        hashMap.put("userPwd", pwd);
        return BizUtil.getBodyFromMap(hashMap);
    }

    private void saveLoginInfo(final String account, final String token) {
        Preferences.saveUserAccount(account);
        Preferences.saveUserToken(token);
    }

    private void initNotificationConfig() {
        // 初始化消息提醒
        NIMClient.toggleNotification(UserPreferences.getNotificationToggle());

        // 加载状态栏配置
        StatusBarNotificationConfig statusBarNotificationConfig = UserPreferences.getStatusConfig();
        if (statusBarNotificationConfig == null) {
            statusBarNotificationConfig = ImCache.getNotificationConfig();
            UserPreferences.setStatusConfig(statusBarNotificationConfig);
        }
        // 更新配置
        NIMClient.updateStatusBarNotificationConfig(statusBarNotificationConfig);
    }

    private void sendRequestRefreshYXToken() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    String newToken = response.getReturnContent().toString();
                    imBean.setToken(newToken);
                    loginIm();
                }
            }
        };
        ApiMethodBoss.refreshYXTokenInBoss(new SimpleLbObserver(listener, otherListener),this,FragmentEvent.DESTROY_VIEW);
    }
}
